import { useMap } from '@/hooks/useMap'

export const useFenceMap = () => {
  const { map, AMap, initMap, destroyMap } = useMap('map-container', { manual: true })
  const mouseTool = ref()
  const district = ref()

  async function initFenceMap() {
    await initMap()

    map.value.on('complete', function () {
      // 画图工具
      mouseTool.value = new AMap.value.MouseTool(map.value)
      //实例化区域边界查询DistrictSearch
      const opts = {
        // showbiz: false,
        subdistrict: 0, //获取边界不需要返回下级行政区
        extensions: 'all' //返回行政区边界坐标组等具体信息
      }
      district.value = new AMap.value.DistrictSearch(opts)
    })
  }

  // 计算多边形区域中心点
  function calculateCenter(lngLatArr: any[]) {
    const total = lngLatArr.length
    let X = 0,
      Y = 0,
      Z = 0
    lngLatArr.map(item => {
      const lng = (item[0] * Math.PI) / 180
      const lat = (item[1] * Math.PI) / 180
      const x = Math.cos(lat) * Math.cos(lng)
      const y = Math.cos(lat) * Math.sin(lng)
      const z = Math.sin(lat)
      X += x
      Y += y
      Z += z
    })
    X = X / total
    Y = Y / total
    Z = Z / total
    const Lng = Math.atan2(Y, X)
    const Hyp = Math.sqrt(X * X + Y * Y)
    const Lat = Math.atan2(Z, Hyp)
    return new AMap.value.LngLat((Lng * 180) / Math.PI, (Lat * 180) / Math.PI)
  }

  // 添加marker点
  function addMarker(position) {
    const marker = new AMap.value.Marker({
      position
    })
    marker.setMap(map.value)
    return marker
  }

  // 清除所有marker点
  function clearMarker() {
    const markers = map.value.getAllOverlays('marker')
    for (let i = 0; i < markers.length; i++) {
      const marker = markers[i]
      removeMarker(marker)
    }
  }

  // 移除marker点
  function removeMarker(marker) {
    marker.setMap(null)
  }

  // 逆地理编码（坐标 -> 地址）
  function getAddress(lnglat) {
    const geocoder = new AMap.value.Geocoder({
      city: '010', //城市设为北京，默认：“全国”
      radius: 1000 //范围，默认：500
    })
    return new Promise((resolve, reject) => {
      geocoder.getAddress(lnglat, function (status, result) {
        if (status === 'complete' && result.regeocode) {
          const addressComponent = result.regeocode.addressComponent
          const partAddress = addressComponent.province + addressComponent.city + addressComponent.district + addressComponent.township
          const fullAddress = partAddress + addressComponent.street + addressComponent.streetNumber

          const formattedAddress = result.regeocode.formattedAddress
          const detailAddress = formattedAddress.replace(partAddress, '')

          resolve({ fullAddress, detailAddress })
        } else {
          console.error('根据经纬度查询地址失败')
          reject()
        }
      })
    })
  }

  return {
    map,
    AMap,
    mouseTool,
    district,
    initFenceMap,
    initMap,
    destroyMap,
    calculateCenter,
    addMarker,
    clearMarker,
    getAddress
  }
}
